package com.hodanet.push;

import android.app.Application;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.util.Log;

import com.umeng.commonsdk.UMConfigure;
import com.umeng.message.IUmengRegisterCallback;
import com.umeng.message.MsgConstant;
import com.umeng.message.PushAgent;
import com.umeng.message.UmengMessageHandler;
import com.umeng.message.UmengNotificationClickHandler;
import com.umeng.message.entity.UMessage;

import org.android.agoo.huawei.HuaWeiRegister;
import org.android.agoo.mezu.MeizuRegister;
import org.android.agoo.oppo.OppoRegister;
import org.android.agoo.vivo.VivoRegister;
import org.android.agoo.xiaomi.MiPushRegistar;


public class UPush {

    public static final String TAG = UPush.class.getSimpleName();

    private PushAgent mPushAgent;

    public void initAndRegister(Application application) {
        try {
            PushUtils.init(application);
            UMConfigure.setLogEnabled(true);
            UMConfigure.init(application, PushConfig.APP_KEY, ChannelConfig.getChannel(), UMConfigure.DEVICE_TYPE_PHONE, PushConfig.APP_SECRET);
            //获取消息推送代理示例
            mPushAgent = PushAgent.getInstance(application);
            //sdk开启通知声音
            mPushAgent.setNotificationPlaySound(MsgConstant.NOTIFICATION_PLAY_SDK_ENABLE);
            //注册推送服务，每次调用register方法都会回调该接口
            mPushAgent.register(new IUmengRegisterCallback() {
                @Override
                public void onSuccess(String deviceToken) {
                    //注册成功会返回deviceToken deviceToken是推送消息的唯一标志
                    Log.e(TAG, "注册成功：deviceToken：-------->  " + deviceToken);
                }

                @Override
                public void onFailure(String s, String s1) {
                    Log.e(TAG, "注册失败：-------->  " + "s:" + s + ",s1:" + s1);
                }
            });
            mPushAgent.setDisplayNotificationNumber(9);
            customStyle();
            onClick();
            initManufacturerPush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * UmengMessageHandler类负责处理消息，包括通知和自定义消息。其中，成员函数getNotification负责定义通知栏样式。
     * 若SDK默认的消息展示样式不符合开发者的需求，可通过覆盖该方法来自定义通知栏展示样式。
     */
    private void customStyle() {
        mPushAgent.setMessageHandler(new UmengMessageHandler() {

            /**
             * 通知的回调方法（通知送达时会回调）
             */
            @Override
            public void dealWithNotificationMessage(Context context, UMessage uMessage) {
                //调用super，会展示通知，不调用super，则不展示通知。
                Log.e(TAG, "dealWithNotificationMessage");
                super.dealWithNotificationMessage(context, uMessage);

            }

            /**
             * 自定义消息的回调方法
             */
            @Override
            public void dealWithCustomMessage(Context context, UMessage uMessage) {
                Log.e(TAG, "dealWithCustomMessage");
                super.dealWithCustomMessage(context, uMessage);
            }

            @Override
            public Notification getNotification(Context context, UMessage msg) {
                return getPushNewsNotification(context, msg);
            }
        });

    }

    public Notification getPushNewsNotification(Context context, UMessage msg) {
        if (Build.VERSION.SDK_INT >= 26) {
            NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            NotificationChannel channel = new NotificationChannel("channel1", "普通通知", NotificationManager.IMPORTANCE_HIGH);
            if (manager != null) {
                manager.createNotificationChannel(channel);
            }
//            PendingIntent pendingIntent = PendingIntent.getActivity(this, NOTIFY_ID /* Request code */, intent, PendingIntent.FLAG_UPDATE_CURRENT);
            Notification.Builder builder = new Notification.Builder(context, "channel1");
            builder
                    .setSmallIcon(R.drawable.ic_launcher)
                    .setWhen(System.currentTimeMillis())
                    .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher))
                    .setContentTitle(msg.title)
                    .setContentText(msg.text)
                    .setAutoCancel(true);
            return builder.build();
        } else {
            Notification.Builder builder = new Notification.Builder(context);
            builder
                    .setSmallIcon(R.drawable.ic_launcher)
                    .setWhen(System.currentTimeMillis())
                    .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher))
                    .setContentTitle(msg.title)
                    .setContentText(msg.text)
                    .setAutoCancel(true);
            return builder.build();
        }
    }


    public void onClick() {
        mPushAgent.setNotificationClickHandler(new UmengNotificationClickHandler() {
            //打开app
            @Override
            public void launchApp(Context context, UMessage uMessage) {
                super.launchApp(context, uMessage);
            }

            //打开url
            @Override
            public void openUrl(Context context, UMessage uMessage) {
                Log.e(TAG, uMessage.url);
                super.openUrl(context, uMessage);
            }

            //打开指定activity
            @Override
            public void openActivity(Context context, UMessage uMessage) {
                super.openActivity(context, uMessage);
                Log.e(TAG, uMessage.activity);
                Log.e(TAG, uMessage.extra.toString());
            }

            //自定义行为
            @Override
            public void dealWithCustomAction(Context context, UMessage uMessage) {
                super.dealWithCustomAction(context, uMessage);
            }
        });
    }

    private void initManufacturerPush() {
        try {
            initMiPush();
//            initHuawei();
            initOppoPush();
            initVivoPush();
//            initMeizuPush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initMiPush() {
        MiPushRegistar.register(PushUtils.getApp(), PushConfig.XIAOMI_APP_ID, PushConfig.XIAOMI_APP_KEY);
    }

    private void initHuawei() {
        HuaWeiRegister.register(PushUtils.getApp());
    }

    private void initOppoPush() {
        //OPPO通道，参数1为app key，参数2为app secret
        OppoRegister.register(PushUtils.getApp(), PushConfig.OPPO_APP_KEY, PushConfig.OPPO_APP_SECRET);
    }

    private void initVivoPush() {
        //vivo 通道
        VivoRegister.register(PushUtils.getApp());
    }

    private void initMeizuPush() {
        //meizu 通道
        MeizuRegister.register(PushUtils.getApp(), PushConfig.MEIZU_APP_ID, PushConfig.MEIZU_APP_KEY);
    }
}
